package by.bsu.scs_bsu.custom_tags;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.apache.log4j.Logger;

public class DefinitionTag extends SimpleTagSupport {
	
	private static final Logger LOGGER = Logger.getLogger("system_logger");
	
	private HashMap screens = null;
	private String definitionName = null;
	private String screenId;
	
	public DefinitionTag() {
		super();
	}
	
	public HashMap getScreens() {
		return screens;
	}
	
	public void setName(String definitionName) {
		this.definitionName = definitionName;
	}
	
	public void setScreen(String screenId) {
		this.screenId = screenId;
	}
	
	public void doTag() {
		try {
			screens = new HashMap();
			
			getJspBody().invoke(null);
			
			Definition definition = new Definition();
			PageContext context = (PageContext) getJspContext();
			ArrayList params = (ArrayList) screens.get(screenId);
			Iterator iterator = null;
			
			if(params != null) {
				iterator = params.iterator();
				while(iterator.hasNext()) {
					definition.setParameter((Parameter) iterator.next());
				}
				context.setAttribute(
						definitionName,
						definition,
						context.APPLICATION_SCOPE);		
			} else {
				LOGGER.debug("DefinitionTag: params are not defined.");
			}
			
		} catch(Exception e) {
			LOGGER.error("DefinitionTag:" + e.toString());
		}
	}	
}
